import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class BatteryLevel extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BatteryLevelState();
  }
}

class _BatteryLevelState extends State<BatteryLevel> {
  static const platform = const MethodChannel('com.hhl.native.io/battery');
  String _batteryLevel = 'Unknown battery level.';
  String _upDateTime = "time";

  //Flutter调用Android 获取电量方法
  Future<Null> _getBatteryLevel() async {
    String batteryLevel;
    var now = new DateTime.now();
    try {
      final int result = await platform.invokeMethod('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }
    setState(() {
      _batteryLevel = batteryLevel;
      _upDateTime = "手动更新时间：$now";
    });
  }

  @override
  void initState() {
    super.initState();
    //Android 主动调用Flutter方法
    platform.setMethodCallHandler((call) => _receiveNaiveNotify(call));
  }

  //接收原生消息通知
  Future<dynamic> _receiveNaiveNotify(MethodCall methodCall) async {
    switch (methodCall.method) {
      case "UpdateBattery":
        var now = new DateTime.now();
        setState(() {
          _batteryLevel = 'Battery level at ${methodCall.arguments} % .';
          _upDateTime = "更新时间：$now";
        });
        return '收到-->${ methodCall.method}';
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("BatteryLevel"),
      ),
      body: Stack(
        children: <Widget>[
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[Text(_batteryLevel), Text(_upDateTime)],
            ),
          ),
          RaisedButton(
            onPressed: () {
              _getBatteryLevel();
            },
            child: Text('获取电量'),
          )
        ],
      ),
    );
  }
}
